#include<QJsonParseError>
#include<QJsonObject>
#include<QJsonArray>
#include "clockstattreemodel.h"
#include "config.h"

ClockStatTreeModel::ClockStatTreeModel(QObject *parent):
    QAbstractItemModel(parent)
{
    _nam = new QNetworkAccessManager(this);
    connect(_nam, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(slot_stat_res(QNetworkReply*)));
    m_rootItem = new TreeItem( {0,0,0,0} );

}
ClockStatTreeModel::~ClockStatTreeModel()
{
    delete m_rootItem;
}

int ClockStatTreeModel::columnCount(const QModelIndex &parent) const
{
    if (parent.isValid())
    {
        return static_cast<TreeItem*>(parent.internalPointer())->columnCount();
    }
    else
    {
        return m_rootItem->columnCount();
    }
}

QHash<int, QByteArray> ClockStatTreeModel::roleNames() const
{
    QHash<int, QByteArray> names(QAbstractItemModel::roleNames());
    names[Qt::DisplayRole] = "display";
    names[TitleRole] = "title";
    names[DayRole] = "day";
    names[DateRole] = "date";
    names[WeekRole] = "week";
    return names;
}

QVariant ClockStatTreeModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
    {
        return QVariant();
    }
    if(role < TitleRole || role > WeekRole){
        return QVariant();
    }
    TreeItem *item = static_cast<TreeItem*>(index.internalPointer());
    if(item)
    {
        QVariant qvar = item->data(role - TitleRole);
        return qvar;
    }

    else
    {
        return QVariant();
    }

    return static_cast<TreeItem*>(index.internalPointer())->data(role - TitleRole);
}

Qt::ItemFlags ClockStatTreeModel::flags(const QModelIndex &index) const
{
    if(!index.isValid())
    {
        return 0;
    }

    return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}

QVariant ClockStatTreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if(orientation == Qt::Horizontal && role == Qt::DisplayRole)
    {
        return m_rootItem->data(section);
    }

    return QVariant();
}

QModelIndex ClockStatTreeModel::index(int row, int column, const QModelIndex &parent) const
{
    if(!hasIndex(row, column, parent))
    {
        return QModelIndex();
    }

    TreeItem *parentItem;
    if(!parent.isValid())
    {
        parentItem = m_rootItem;
    }
    else
    {
        parentItem = static_cast<TreeItem*>(parent.internalPointer());
    }

    TreeItem *childItem = parentItem->child(row);
    if(childItem)
    {
        return createIndex(row, column, childItem);
    }
    else
    {
        return QModelIndex();
    }
}

QModelIndex ClockStatTreeModel::parent(const QModelIndex &index) const
{
    if(!index.isValid())
    {
        return QModelIndex();
    }

    TreeItem *childItem = static_cast<TreeItem*>(index.internalPointer());
    TreeItem *parentItem = childItem->parent();

    if(parentItem == m_rootItem)
    {
        return QModelIndex();
    }
    return createIndex(parentItem->row(), 0, parentItem);
}
bool ClockStatTreeModel::hasParent(const QModelIndex &index) const
{
    if(!index.isValid())
    {
        return false;
    }

    TreeItem *childItem = static_cast<TreeItem*>(index.internalPointer());
    TreeItem *parentItem = childItem->parent();

    if(parentItem == m_rootItem)
    {
        return false;
    }

    return true;
}

int ClockStatTreeModel::rowCount(const QModelIndex &parent) const
{
    TreeItem *parentItem;
    if(parent.column() > 0)
    {
        return 0;
    }

    if(!parent.isValid())
    {
        parentItem = m_rootItem;
    }
    else
    {
        parentItem = static_cast<TreeItem*>(parent.internalPointer());
    }

    return parentItem->childCount();
}

QAbstractItemModel *ClockStatTreeModel::model()
{
    return this;
}

void ClockStatTreeModel::slot_stat_res(QNetworkReply * reply)
{
    int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    qDebug()<<status;

    if (reply->error() == QNetworkReply::NoError) {
        QByteArray alldata = reply->readAll();
        QJsonParseError jsonpe;
        QJsonDocument json = QJsonDocument::fromJson(alldata, &jsonpe);
        if (jsonpe.error == QJsonParseError::NoError)
        {
            if (json.isObject()) {
                QJsonObject obj = json.object();
                int code = obj["status"].toInt();
                QString msg = obj["msg"].toString();
                if (code == 1) {
                    QJsonObject data = obj["data"].toObject();
                    QJsonArray labels = data["labels"].toArray();
                    beginResetModel();
                    for(int i=0;i<labels.count();i++){
                        QJsonObject label = labels.at(i).toObject();
                        QString statusLabel = label["statusLabel"].toString();
                        QJsonArray clocks = label["clocks"].toArray();
                        auto item = new TreeItem({statusLabel,clocks.count(),0,0});
                        for(int j=0;j<clocks.count();j++){
                            QJsonObject clock = clocks.at(j).toObject();
                            item->appendChild(new TreeItem({
                                                               0,
                                                               0,
                                                               clock["clock_date"].toString(),
                                                               "星期"+clock["clock_week"].toString()
                                                           }));
                        }
                        m_rootItem->appendChild(item);
                    }
                    endResetModel();
                }
            }

        };
    }
    else {
        qDebug() << reply->error();
    }
    reply->deleteLater();
}

void ClockStatTreeModel::slot_stat_req(QString user_id){
    QString url = API_URL+"clock/stat";
    url+="?user_id="+user_id;
    QUrl qurl(url);
    QNetworkRequest req(qurl);
    _nam->get(req);

}
